from business.UnpackedData import UnpackedData 
from business.MftFile import MftFile 
from business.MappingFile import MappingFile 

from usecase.DecryptFile import DecryptFile

import logging

class Gw2Dat:
    def __init__(self):
        self.mHeaderDataDef = UnpackedData("Gw2DatHeader",
                                           [["id"        , "4s"],
                                            ["headerSize", "I"] ,
                                            ["unknown1"  , "I"] ,
                                            ["blockSize" , "I"] ,
                                            ["crc"       , "I"] ,
                                            ["unknown2"  , "I"] ,
                                            ["mftOffset" , "Q"] ,
                                            ["mftSize"   , "I"] ,
                                            ["flags"     , "I"]])
        self.mHeader = None
        self.mMftFile = MftFile()
        self.mMappingFile = MappingFile()
        
    def parse(self, iDatPath):
        logging.info("Parsing Gw2Day file: " + str(iDatPath))
        with open(iDatPath, "rb") as lDatFile:
            self.mHeader = self.mHeaderDataDef.unpackFromFile(lDatFile)
            logging.debug(self.mHeader)
            
            # Entry 0 is the header / entry 1 is the mapping / entry 2 is the MftFile
            # Entry in the header is manifest
            self.mMftFile.parse(lDatFile, self.mHeader.mftOffset, self.mHeader.mftSize)
            
            lMappingFileEntry = self.mMftFile.mEntries[1]
            
            # File ID 3 is localPref / 12 is a CD Key ? / 2 is unknown
            # File ID 4097 is DEPSEARCH
            self.mMappingFile.parse(lDatFile, lMappingFileEntry.fileOffset, lMappingFileEntry.fileSize) 
            
            lFileNumber = self.mMappingFile.getFileIndex(79998)
            lDecryptFile = DecryptFile()
            
            lOutput = lDecryptFile.decrypt(lDatFile, self.mMftFile.getFile(lFileNumber).fileOffset, self.mMftFile.getFile(lFileNumber).fileSize)
            
            if lOutput:
                lFile = open("..\\..\\..\\dump", "wb")
                lFile.write(lOutput)
                lFile.close()
            
            